package com.tql.view.controller;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.tql.view.pojo.Scenery;
import com.tql.view.service.SceneryService;
import org.apache.ibatis.annotations.Param;
import org.apache.lucene.queries.SearchAfterSortedDocQuery;
import org.attoparser.dom.IDOMMarkupParser;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.naming.directory.SearchResult;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
public class SearchController {
    @Autowired
    private SceneryService sceneryService;
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @RequestMapping("/mysearch")
    public String test1(){
        return "/search";
    }
    //批量插入数据
    @RequestMapping("/mysearch2/{search}")
    @ResponseBody
    public String test2(@PathVariable("search")String search) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        List<Scenery> scenery = sceneryService.getScenery(search,2,10);
        if (scenery.size()<=0) {
            return "HELLO";
        }
        bulkRequest.timeout("3s");
        try {
            //批量插入
            for (int i=0;i<scenery.size();i++){
                bulkRequest.add(new IndexRequest("scenery")
                        .source(JSON.toJSONString(scenery.get(i)), XContentType.JSON));
            }
            BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            System.out.println(bulk.status());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
        return "ok";
    }
    //批量插入数据
    @RequestMapping("/mysearch4/id")
    @ResponseBody
    public String test7(@PathVariable("id")String id) throws IOException {
        IndexRequest request = new IndexRequest("scenery");// 没有id会自动生成一个随机ID
        Scenery sceneryById = sceneryService.getSceneryById(id);

        request.source(JSON.toJSONString(sceneryById),XContentType.JSON);
        IndexResponse index = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        System.out.println(index.status());// created
        return "ok";
    }
    @RequestMapping("/search3/{keyword}")
    @ResponseBody
    public String test3(@PathVariable("keyword") String keyword) throws IOException {
        //创建查询条件请求对象
        SearchRequest searchRequest = new SearchRequest("scenery");
        //构造搜索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //精确匹配
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("mytype", keyword);
        MatchQueryBuilder matchAllQueryBuilder = QueryBuilders.matchQuery("describes",keyword);
        //创建高亮
        searchSourceBuilder.highlighter(new HighlightBuilder());
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        // (3)条件投入
        searchSourceBuilder.query(matchAllQueryBuilder);
        //添加条件到请求
        searchRequest.source(searchSourceBuilder);
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = search.getHits();
        SearchHit[] hits1 = hits.getHits();
        System.out.println(hits);
        System.out.println(search.getSuccessfulShards());
        //存放数据
        List<Object> list = new ArrayList<>();
        for (SearchHit documentFields : hits.getHits()) {
            System.out.println(documentFields.getSourceAsMap());
            Map<String, Object> params = documentFields.getSourceAsMap();
            list.add(params);

        }
        return JSON.toJSONString(list);
    }

}
